package com.synway.handler;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by mx on 2020/4/12.
 */
@Slf4j
public class StreamThread extends Thread {
    // 输入流
    private InputStream inputStream;
    // 流类型
    private String streamType;
    // 是否运行完成
    private volatile boolean inFinish = false;
    // 需要的返回结果数据
    private Map<String, JSONArray> resultMap;

    /**
     * 构造器
     *
     * @param inputStream 输入流
     * @param streamType 流类型
     */
    public StreamThread(InputStream inputStream, String streamType) {
        this.inputStream = inputStream;
        this.streamType = streamType;
        this.inFinish = false;
        this.resultMap = new HashMap<>();
    }
    @Override
    public void run() {
        try {
            InputStreamReader isr = new InputStreamReader(inputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(isr);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (streamType.equals("Error")) {
                    log.error(">>>>>>Error :" + line);
                } else {
                    log.info("info:" + line);
                }
            }
            isr.close();
            bufferedReader.close();
        } catch (IOException e) {
            log.error("Exception:" + e);
        } finally {
            this.inFinish = true;
            synchronized (this) {
                notify();
            }
        }
    }

    /**
     *
     * 返回结果
     *
     * @return
     *
     * @author weijs
     * @date 2018年9月28日 下午1:37:42
     */
    public Map<String, JSONArray> getContent() {
        if (!this.inFinish) {
            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException ignore) {
                    ignore.printStackTrace();
                }
            }
        }
        return this.resultMap;
    }
}
